package com.example.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * @Date 2022/6/12
 * @Author  Jonathan
 */
@Slf4j
@Component
public class LuaService implements ApplicationRunner {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Resource(name = "compareAndSetScript")
    private DefaultRedisScript<Long> compareAndSetScript;


    @Override
    public void run(ApplicationArguments args) throws Exception {

        try {
            testLua();
        } catch (Exception e) {
            log.error("error:", e);
        }

    }

    public void testLua() {
        log.info("测试lua脚本。");
        String key = "uid_100";
        final List<String> keys = Arrays.asList(key);
        String uname = "zhangsan";
        Long ret = redisTemplate.execute(this.compareAndSetScript, keys, uname);
        print(ret, key, uname);
        final String s = redisTemplate.opsForValue().get(key);
        log.info("s:{}", s);
        uname = "lisi";
        ret = redisTemplate.execute(this.compareAndSetScript, keys, uname);
        print(ret, key, uname);
    }

    private void print(Long ret, String key, String uname) {
        if (ret == 0) {
            log.info("不用修改:{}", key);
        } else {
            log.info("{}修改:{}", key, uname);

        }
    }
}
